package com.example.ch02_student.adminsDo;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.ch02_student.R;
import com.example.ch02_student.entity.Course;
import com.example.ch02_student.entity.Grade;
import com.example.ch02_student.entity.Student;
import com.example.ch02_student.utils.DataBean;
import com.example.ch02_student.utils.ResultVo;
import com.example.ch02_student.utils.RoleInfo;
import com.example.ch02_student.utils.UrlBase;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.SneakyThrows;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StudentInfo extends AppCompatActivity {
    private OkHttpClient okHttpClient;
    private ListView lv;
    private List<Map<String, String>> list;
    private AlertDialog dialog = null;
    private static String[] cclass;//班级
    private static String[] major;//专业
    private static String[] college;//学院
    private Spinner spinner;
    private String xzcclass = "", xzmajor = "", xzcollege = "";
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");


    @SneakyThrows
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_info);
        okHttpClient = new OkHttpClient();
        lv = findViewById(R.id.stuLv);

        spinner=findViewById(R.id.spinner);
        init();
        Thread.sleep(1000);
        spinnerClass();
if (RoleInfo.INT_ROLE==1||RoleInfo.PERSSIONS.contains("uGraInfo")){
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String, String> map = list.get(i);
                String sno = map.get("sno");
                Bundle bundle = new Bundle();
                bundle.putString("sno", sno);
                Intent intent = new Intent(StudentInfo.this, StudentGradeUpdate.class);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
    }else{
    Toast.makeText(StudentInfo.this,"无此权限",Toast.LENGTH_SHORT).show();
    }
        //spinner 点击事件
      spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
              xzcclass=cclass[i];
              Toast.makeText(StudentInfo.this,xzcclass,Toast.LENGTH_SHORT).show();
          }
          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {

          }
      });

    }

    //初始化页面
    public void init() {
        //selectAllGrade
        //班级 专业 学院
        Request build = new Request.Builder().url(UrlBase.URL_BASE + "/student/selectAllGrade").build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                xuanran(string);
            }
        });
    }

    //数据渲染
    public void xuanran(String json) {
        //解析
        ResultVo resultVo = new Gson().fromJson(json, ResultVo.class);
        List<DataBean> data = resultVo.getData();
        list = new ArrayList<>();
        Map<String, String> map;
        System.err.println(data);
        if (data != null && data.size() > 0) {
            final String[] s = new String[]{"sno", "sname", "sex", "cclass", "major", "tel",
                    "college", "age", "createTime", "cname0", "cname1", "cname2", "cname3", "grade0", "grade1", "grade2", "grade3"};
            final int[] ints = new int[]{R.id.sno, R.id.sname, R.id.ssex, R.id.scclass, R.id.smajor
                    , R.id.stel, R.id.scollege, R.id.sage, R.id.screateTime, R.id.course1, R.id.course2, R.id.course3, R.id.course4
                    , R.id.grade1, R.id.grade2, R.id.grade3, R.id.grade4};

            for (int i = 0; i < data.size(); i++) {
                //得到每个StudentVo
                DataBean dataBean = data.get(i);
                map = new HashMap<>();
                map.put("sno", dataBean.getSno());
                map.put("sname", dataBean.getSname());
                map.put("sex", dataBean.getSex());
                map.put("cclass", dataBean.getCclass());
                map.put("major", dataBean.getMajor());
                map.put("tel", dataBean.getTel());
                map.put("college", dataBean.getCollege());
                map.put("age", dataBean.getAge() + "");
                if (dataBean.getCreateTime() != null) {
                    map.put("createTime", simpleDateFormat.format(dataBean.getCreateTime()));
                }

                //填充课程名称及分数
                for (int j = 0; j < dataBean.getCourses().size(); j++) {
                    Course course = dataBean.getCourses().get(j);
                    map.put("cname" + j, course.getCname() + "(" + course.getCno() + ")");
                }
                for (int k = 0; k < dataBean.getGrades().size(); k++) {
                    Grade grade = dataBean.getGrades().get(k);
                    map.put("grade" + k, grade.getScore() + "");
                }
                list.add(map);
                //准备simpleAdapter数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SimpleAdapter simpleAdapter = new SimpleAdapter(StudentInfo.this, list, R.layout.activity_student_info_items, s, ints);
                        lv.setAdapter(simpleAdapter);
                    }
                });
                System.err.println(list);

            }
        }
    }

    //筛选条件 班级
    public void cclass(View view) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i).get("cclass"));
        }
        cclass = new String[set.size()];
        Iterator<String> iterator = set.iterator();
        int a = 0;
        //set集合的值赋给String[];
        while (iterator.hasNext()) {
            cclass[a] = iterator.next();
            a++;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(StudentInfo.this)
                .setTitle("选择班级")
                .setSingleChoiceItems(cclass, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        xzcclass = cclass[i];
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
        Toast.makeText(StudentInfo.this, xzcclass + "", Toast.LENGTH_SHORT).show();
    }

    //筛选条件 专业
    public void major(View view) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i).get("major"));
        }
        major = new String[set.size()];
        Iterator<String> iterator = set.iterator();
        int a = 0;
        //set集合的值赋给String[];
        while (iterator.hasNext()) {
            major[a] = iterator.next();
            a++;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(StudentInfo.this)
                .setTitle("选择班级")
                .setSingleChoiceItems(major, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        xzmajor = major[i];
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
        Toast.makeText(StudentInfo.this, xzmajor + "", Toast.LENGTH_SHORT).show();
    }

    //筛选条件 学院
    public void college(View view) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i).get("college"));
        }
        college = new String[set.size()];
        Iterator<String> iterator = set.iterator();
        int a = 0;
        //set集合的值赋给String[];
        while (iterator.hasNext()) {
            college[a] = iterator.next();
            a++;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(StudentInfo.this)
                .setTitle("选择班级")
                .setSingleChoiceItems(college, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        xzcollege = college[i];
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
        Toast.makeText(StudentInfo.this, xzcollege + "", Toast.LENGTH_SHORT).show();
    }

    //搜索按钮
    public void selectSearch(View view) {
        Request build = new Request.Builder().url(UrlBase.URL_BASE + "/student/selectStuMulti?cclass=" + xzcclass + "&major=" + xzmajor + "&college=" + xzcollege).build();
        Call call = okHttpClient.newCall(build);
        System.err.println(UrlBase.URL_BASE + "/student/selectStuMulti?sex=null&cclass=" + xzcclass + "&major=" + xzmajor + "&college=" + xzcollege);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String json = response.body().string();
                ResultVo resultVo = new Gson().fromJson(json, ResultVo.class);
                if (resultVo.getCode() == 1000) {
                    xuanran(json);
                } else {
                    System.err.println("error");
                }
            }
        });
    }

    //打印成绩表
    public void printGrade(View view) {
        //exportStudentGrade

        Uri uri = Uri.parse(UrlBase.URL_BASE + "/teacher/exportStudentGrade?cclass=" + xzcclass + "&major=" + xzmajor + "&college=" + xzcollege);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);

    }

    //柱状图分析
    public void columnPhoto(View view) {
        Intent intent = new Intent(StudentInfo.this, ColumnPhoto.class);
        startActivity(intent);
    }

    //折线图分析
    public void linePhoto(View view) {
        startActivity(new Intent(StudentInfo.this, LinePhoto.class));
    }

    public void back(View view) {
        if (RoleInfo.INT_ROLE == 1) {
            startActivity(new Intent(StudentInfo.this, AdminsDo.class));
        } else {
            startActivity(new Intent(StudentInfo.this, AdminsDo.class));
        }

    }

    //设置班级下拉列表
    public void spinnerClass(){
        Set<String> set = new HashSet<>();
        List dataList=new ArrayList();

        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i).get("cclass"));
        }
        cclass = new String[set.size()+1];
        Iterator<String> iterator = set.iterator();
        dataList.add("班级");
        cclass[0]="";
        int a = 1;
        //set集合的值赋给String[];
        while (iterator.hasNext()) {
            cclass[a] = iterator.next();
            //
            dataList.add(cclass[a]);
            a++;

        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(StudentInfo.this,R.layout.spring_items,dataList);
        spinner.setAdapter(arrayAdapter);
    }



}
